package com.ctu.gzero.edit
{
	import com.ctu.gzero.elements.DOMElement;
	import com.ctu.gzero.elements.ParaElement;
	import com.ctu.gzero.elements.RunElement;
	
	public class ElementRange
	{
		public var firstRun:RunElement;
		public var firstPara:ParaElement;
		public var lastRun:RunElement;
		public var lastPara:ParaElement;
		
		public function ElementRange()
		{
		}
		
		public static function createElementRange(dom:DOMElement, beginIndex:int, endIndex:int):ElementRange
		{
			var paraListLength:int = 0;			
			var elementRange:ElementRange = new ElementRange();
			
			paraListLength = dom.paraList.length;
			
			for(var i:int=0; i<paraListLength; i++)
			{
				var para:ParaElement = dom.getPara(i);
				if(beginIndex >= para.absoluteStart && beginIndex <= para.absoluteStart + para.textLength-1)
				{
					elementRange.firstPara = para;
					elementRange.firstRun = getTargetRun(para, beginIndex);
				}
				
				if(endIndex >= para.absoluteStart && endIndex <= para.absoluteStart + para.textLength -1)
				{
					elementRange.lastPara = para;
					elementRange.lastRun = getTargetRun(para, endIndex);
				}
			}
			
			return elementRange;
		}
		
		public static function getTargetRun(para:ParaElement, targetIndex:int):RunElement
		{
			var runListLength:int = 0;
			var targetRun:RunElement;
			
			runListLength = para.runList.length;
			
			for(var i:int=0; i< runListLength; i++)
			{
				var run:RunElement = para.getRun(i);
				if(targetIndex >= run.absoluteStart && targetIndex <= run.absoluteStart + run.textLength)
				{
					targetRun = run;
					break;
				}
			}
			
			return targetRun;
		}
	}
}